<?php
declare(strict_types=1);
namespace app\admin\model;
use aphp\core\Model;
// 配置分组
class ConfigGroup extends Model
{
    protected string $table = 'config_group';
    protected string $pk = 'id';
    protected array $validate = [
        ['title', 'required|unique', '标题必须|标题已存在', IF_MUST, AC_BOTH],
        ['memo', 'required', '请输入备注', IF_MUST, AC_BOTH],
        ['app', 'alpha_dash', '应用名称格式错误', IF_MUST, AC_BOTH],
        ['sign', 'alpha_dash|unique:config_group.id,sign,app=_app', '标识格式错误|标识已存在', IF_MUST, AC_BOTH],
        ['sign', 'checkSign', '文件标识不能是内置配置', IF_MUST, AC_BOTH],
        ['sort', 'number', '排序必须是正数', IF_MUST, AC_BOTH],
    ];
    protected array $auto = [
        ['status', '1', 'string', IF_MUST, AC_INSERT],
    ];

    public function checkSign($value, string $field, string $params, array $data): bool
    {
        $deny_sign = ['app','cache','cms','cookie','database','debug_bar','filter','middleware','pagination','response','route','session','template','upload', 'view'];
        return !in_array($value, $deny_sign);
    }

    protected function _before_delete(array $data): void
    {
        $this->db = $this->db->where('id>2 AND is_sys=0'); // 禁止删除
    }

    protected function _after_delete(array $data): void
    {
        // 删除配置数据
        db('config')->where('group_id', $data['id'])->delete();
        // 删除配置文件
        $file = ($data['app'] == 'common') ? ROOT_PATH . '/config/'.$data['sign'].'.php' : ROOT_PATH . '/app/'.$data['app'].'/config/'.$data['sign'].'.php';
        if (is_file($file)) {
            unlink($file);
        }
    }
}